<template>
	<view class="view-contain">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module leftIcon="arrow-left" :title="title" />
		<view class="content">
			<rich-text :nodes="wrapContent|formatRichText" />
			<!-- 显示附件 -->
			<view v-if="attachmentUrl" class="attachment">
				<text>附件: </text>
				<!-- 修改：添加 @click 事件绑定 -->
				<view @click="downloadAttachment(attachmentUrl)"
					style="color: #007aff; text-decoration: underline; cursor: pointer;">
					{{ getCleanFileName(attachmentUrl.split('/').pop()) }}
				</view>
				<view v-if="shareFilePath" class="share-btn" @click="shareFile">
					<u-button>分享下载的文件</u-button>
				</view>
			</view>
			<!-- 收藏按钮 -->
			<view class="right-buttons">
				<view class="add-collect-btn" @click="addCollect">
					<u-icon :name="isCollected ? 'heart-fill' : 'heart'" :color="isCollected ? 'red' : '#000'"
						:style="{'-webkit-text-stroke-width': isCollected ? '0px' : '1px', '-webkit-text-stroke-color': isCollected ? 'red' : '#000', 'color': isCollected ? 'red' : '#fff'}"
						size="36"></u-icon>
				</view>
				<!-- 将 add-article-btn 移到 right-buttons 容器内 -->
				<view class="add-article-btn" @click="addArticle">
					<u-icon name="plus" color="#FFFFFF" size="24"></u-icon>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import baseUrl from '@/config/baseUrl'; // 引入 baseUrl
	import {
		collectAdd,userPointsCheck
	} from "@/config/api.js";

	export default {
		data() {
			return {
				title: '好文分享',
				wrapContent: '',
				attachmentUrl: '',
				shareFilePath: '', // New property to store the shared file path
				id: null, // 新增 id 变量
				channelId: null, // 新增 channelId 变量
				// 添加 isCollected 变量并初始化为 false
				isCollected: false
			};
		},
		filters: {
			formatRichText(html) {
				if (html) {
					let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
						if (match.search(/style=/gi) === -1) {
							match = match.replace(/\<img/gi, '<img style=""');
						}
						return match;
					});

					newContent = newContent.replace(/style="/gi, '$& max-width:100% !important;');
					return newContent;
				}
			}
		},
		computed: {},
		onLoad(option) {
			if (option.content) {
				const content = decodeURIComponent(option.content);
				const convertedContent = content.replace(/<pre/g, '<div').replace(/<\/pre>/g, '</div>');
				this.wrapContent = `<div style="word-wrap: break-word; white-space: pre-wrap;">${convertedContent}</div>`;
			}
			
			if (option.attachment !== 'null') {
				this.attachmentUrl = `${baseUrl.baseUrl}${option.attachment}`;
				console.log('附件URL:', this.attachmentUrl);
			} else {
				// 明确设置为空，确保v-if判断为false
				this.attachmentUrl = '';
				console.log('无有效附件');
			}

			if (option.id && option.channelId) {
				this.id = option.id; // 保存 id 到组件 data 中
				this.channelId = option.channelId; // 保存 channelId 到组件 data 中
			}
		},
		onShareAppMessage() {
			return {
				title: '来苏榜，看大神经验！',
				imageUrl: "../../static/img/share.jpg",
				path: '/pages/articles/index'
			};
		},
		methods: {
			// 新增方法：提取文件名并去掉下划线后面的内容
			getCleanFileName(fullName) {
				const parts = fullName.split('_');
				const extension = fullName.split('.').pop();
				return `${parts[0]}.${extension}`;
			},
			// Download attachment
			async downloadAttachment(url) {
				try {
					const userPointsResult  = await userPointsCheck({
						action: 'downloadArticle'
					});
					
					if (userPointsResult.code !== 200) {
						return uni.$u.toast('用户积分不足，无法完成操作，请努力赚积分！');
					}
					
					const lastSlashIndex = url.lastIndexOf('/');
					const underscoreIndex = url.indexOf('_', lastSlashIndex);
					const fileName = url.substring(lastSlashIndex + 1, underscoreIndex);
					const fileExtension = url.substring(url.lastIndexOf('.'));
					console.log('Original URL:', url); // 输出原始 URL，方便调试

					const res = await uni.downloadFile({
						url: url // 直接使用原始 URL 进行下载
					});
					// 假设 res 是一个数组，从第二个元素获取状态码
					const actualRes = Array.isArray(res) ? res[1] : res;
					console.log('Actual Download response:', actualRes); // 输出实际的下载响应信息
					// 检查下载结果
					if (actualRes.statusCode === 200) {
						const tempFilePath = actualRes.tempFilePath;
						// 保存到本地文件系统
						const savedFilePath = await new Promise((resolve, reject) => {
							wx.getFileSystemManager().saveFile({
								tempFilePath: tempFilePath,
								filePath: wx.env.USER_DATA_PATH + '/' + fileName +
									fileExtension, // 使用提取的文件名和后缀
								success: function(res) {
									const savedFilePath = res.savedFilePath;
									this.shareFilePath = savedFilePath; // 保存分享文件路径
									resolve(savedFilePath); // 确保返回保存的文件路径
									// sendFileToChat(savedFilePath); // 这里如果没有定义该方法，建议注释掉
								}.bind(this),
								fail: function(err) {
									console.log('保存文件失败：', err);
									reject(err); // 处理失败情况
								}
							});
						});
					} else {
						throw new Error('下载失败，未获取到文件路径');
					}
				} catch (error) {
					console.error('下载失败:', error, 'URL:', url); // 输出错误信息和 URL
					uni.showToast({
						title: '下载失败，请检查网络或链接',
						icon: 'none'
					});
				}
			},
			shareFile() {
				if (this.shareFilePath) {
					wx.shareFileMessage({
						filePath: this.shareFilePath,
						success: function() {
							console.log('文件已成功分享');
						},
						fail: function(err) {
							console.log('分享文件失败：', err);
						}
					});
				} else {
					uni.$u.toast('没有文件可以分享');
				}
			}, // 新增方法：跳转到add.vue页面
			addArticle() {
				uni.navigateTo({
					url: '/pages/articles/components/add'
				});
			},
			// 新增收藏方法
			async addCollect() {
				try {
					const targetState = !this.isCollected;
					let collectType = '';
					if (this.channelId == 0) {
						collectType = '上岸经验';
					} else if (this.channelId == 5) {
						collectType = '苏榜原创';
					}

					const res = await collectAdd({
						collectId: this.id,
						collectType: collectType,
						isCollected: targetState ? 1 : 0 // 明确转换为1/0格式
					});
					if (res.code === 200) {
						this.isCollected = targetState; // 更新前端状态
						uni.showToast({
							title: targetState ? '收藏成功' : '取消收藏',
							icon: 'success'
						});
					} else if (res.code === 500 && res.msg === "用户已收藏") {
						this.isCollected = targetState; // 更新前端状态
						uni.showToast({
							title: targetState ? '收藏成功' : '取消收藏',
							icon: 'success'
						});
					}
				} catch (error) {
					console.error('收藏操作失败:', error);
					// 不需要手动回滚状态，因为操作失败时状态未改变
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.view-contain {
		position: relative;
		height: 100vh;
		background-color: #f9f9f9;
	}

	.content {
		padding: 24rpx 24rpx;
		line-height: 1.7;
		letter-spacing: 0.05em;
		font-size: 32rpx;
		color: #333;
	}

	.content rich-text p,
	.content rich-text h1,
	.content rich-text h2,
	.content rich-text h3,
	.content rich-text h4,
	.content rich-text h5,
	.content rich-text h6 {
		margin-bottom: 24rpx;
	}

	.content rich-text img {
		margin-bottom: 24rpx;
		display: block;
		margin-left: auto;
		margin-right: auto;
	}

	.attachment {
		margin-top: 24rpx;
		color: #007aff;
		text-decoration: underline;
		cursor: pointer;
	}

	.share-btn {
		margin-top: 10px;
	}

	// 新增收藏按钮样式
	.right-buttons {
		position: fixed;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.add-like-btn,
	.add-collect-btn {
		/* 去掉外框背景 */
		background-color: transparent;
		border-radius: 0;
		width: auto;
		height: auto;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	// 新增文章按钮样式
	.add-article-btn {
		background-color: #007aff;
		width: 40px;
		height: 40px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		// 移除固定定位相关样式
		position: static;
		bottom: auto;
		right: auto;
	}
</style>